package com.fitness.front.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fitness.front.convertor.CoachCommentConvertor;
import com.fitness.front.mapper.CoachCommentMapper;
import com.fitness.front.mapper.CoachMapper;
import com.fitness.front.mapper.MemberMapper;
import com.fitness.front.modal.coach.dto.CoachCommentDto;
import com.fitness.front.modal.coach.entity.Coach;
import com.fitness.front.modal.coach.entity.CoachComment;
import com.fitness.front.modal.coach.param.CoachCommentQueryParams;
import com.fitness.front.modal.coach.vo.CoachCommentVO;
import com.fitness.front.modal.member.entity.Member;
import com.fitness.front.service.ICoachCommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CoachCommentServiceImpl extends ServiceImpl<CoachCommentMapper, CoachComment> implements ICoachCommentService {

    private final CoachCommentConvertor coachCommentConvertor;
    private final MemberMapper memberMapper;
    private final CoachMapper coachMapper;

    @Override
    public Page<CoachCommentVO> getCoachCommentPage(CoachCommentQueryParams queryParams) {
        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        Page<CoachComment> page = new Page<>(pageNum, pageSize);

        // 查询数据
        Page<CoachComment> pageVo = this.baseMapper.getCoachCommentPage(page, queryParams);
        Page<CoachCommentVO> retPage = coachCommentConvertor.entity2Vo(pageVo);
        if(pageVo.getTotal() > 0){
            List<Long> tmp = pageVo.getRecords().stream().map(CoachComment::getMemberId).collect(Collectors.toList());
            List<Member> members = memberMapper.getMapById(tmp);
            Map<Long,Member> memberMap = new HashMap<>();
            members.forEach(member -> memberMap.put(member.getId(), member));
            retPage.getRecords().forEach((vo)->{
                Member member = memberMap.get(vo.getMemberId());
                if(member != null){
                    vo.setAvatar(StrUtil.isBlank(member.getAvatar()) ? null : member.getAvatar());
                }
            });
            return retPage;
        }
        return retPage;
    }

    @Override
    public boolean addCoachComment(CoachCommentDto commentDto) {
        Long coachId = commentDto.getCoachId();
        Coach coach = coachMapper.selectById(coachId);
        commentDto.setRealName(coach.getRealName());
        CoachComment courseComment = coachCommentConvertor.dto2Entity(commentDto);
        return this.baseMapper.insert(courseComment) > 0;
    }

    @Override
    public boolean updateCoachComment(CoachCommentDto commentDto) {
        return false;
    }
}
